<?php
class Questions extends MY_Front_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('questions_model');
		$this->load->model('user_model');
	}
	
	public function index(){
		redirect('show_questions');
	}
	
	function show_questions($searchString = ''){
		$data = array();
		
		$search = array();
		$search['language_id'] = $this->config->item('lang_obj')->id;
		
		if (strlen($searchString)){
			$search['keyword'] = $searchString;
			$data['keyword'] = $searchString;
		}
		
		$data['questions'] = $this->questions_model->getAnswered($search)->result();
		
		$this->template->add_js('application/assets/js/jqueryPlugins/jquery.pajinate.min.js');
		$this->template->add_js('application/assets/js/questions.js');
		
		$data['experts'] = $this->user_model->get_by_param(array('language_id' => $this->config->item('lang_obj')->id));
		
		$this->template->write_view('content','front/questions.php',$data);
		$this->template->write_view ( 'footer', 'templates/front/footer.php', array('hide_questions' => 1) ,true);
		$this->template->render();
	}
	
	function get_question($id = 0){
		if ($id){
			$question = $this->questions_model->get_by_id($id);
			$question->views++;
			
			$html = '<div>' . lang('asked_by') . ' ' . (isset($question->user_name) ? $question->user_name : lang('anonimus')) . '</div>';
			$html .= '<div>' . $question->question . '</div>';
			
			if ($question->answered_by){
				$html .= '<div style="margin-top:50px;">' . lang('answered_by') . ' ' . (isset($question->answered_by_user) ? $question->answered_by_user : lang('anonimus')) . '</div>';
				$html .= '<div>' . $question->answer . '</div>';
			}
	
			$question->update();
			
			echo json_encode(array('status' => 1, 'html' => $html));
		} else {
			echo json_encode(array('status' => 0));
		}
	}
	
	function save_question(){
		$this->load->model('questions_model');
		$search = array();
		
		parse_str($this->input->post('form_data'),$search);
		
		$questionsObj = new questions_model();

		$questionsObj->question = $search['question'];
		$questionsObj->language_id = $this->config->item('lang_obj')->id;
		$questionsObj->data = date('Y-m-d H:i:s');
		
		if ($this->session->userdata('user')){
			$user = $this->session->userdata('user'); 
			$questionsObj->user_id = $user['id'];
		}
		
		$id = $questionsObj->insert();
		
		if ($id){
			echo json_encode(array('status' => 1));
		} else {
			echo json_encode(array('status' => 0));
		}
	}
}